package cn.lwx.javaweb.utils;

import java.sql.*;
import java.util.ResourceBundle;

/**
 * JDBC工具类
 *
 * @author lwx
 * @date 2021-05-18
 */
public class JDBCUtils {

	// 构造方法私有化，防止new对象
	private JDBCUtils() {}

	// 静态变量与静态代码块执行时间一致
	// 类加载时绑定属性资源文件
	private  static ResourceBundle bundle = ResourceBundle.getBundle("resources/jdbc");

	// 注册驱动
	static {
		try {
			Class.forName(bundle.getString("driver"));
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	// 取得连接
	public static Connection getConnection() throws SQLException {
		String url = bundle.getString("url");
		String user = bundle.getString("user");
		String password = bundle.getString("password");
		Connection conn = DriverManager.getConnection(url, user, password);
		return conn;
	}


	/**
	 * 释放资源
	 * @param rs 查询结果集
	 * @param stmt 数据库操作对象
	 * @param conn 连接对象
	 */
	public static void close(ResultSet rs, Statement stmt, Connection conn) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (stmt != null) {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
